/* +----------------------------------------------------------------------
| 麦沃德科技赋能开发者，助力中小企业发展 
+----------------------------------------------------------------------
| Copyright (c) 2017～2024  www.wdadmin.cn    All rights reserved.
+----------------------------------------------------------------------
| 沃德代驾系统并不是自由软件，不加密，并不代表开源，未经许可不可自由转售和商用
+----------------------------------------------------------------------
| Author: MY WORLD Team <bd@maiwd.cn>   www.wdadmin.cn
+---------------------------------------------------------------------- */

class WebsocketUtil {
	// 构造函数，初始化 WebSocket 连接
	constructor(url, time) {
		this.url = url; // WebSocket 服务器的 URL
		this.time = time; // 心跳发送的间隔时间（秒）
		this.socketTask = null; // WebSocket 任务对象
		this.isOpen = false; // WebSocket 连接是否打开
		this.reconnectTimeout = null; // 重连定时器
		this.heartbeatInterval = null; // 心跳定时器
		this.messageCallbacks = []; // 存储外部注册的消息回调函数的数组
		this.isWorking = true; // 是否在运行中

		// 初始化 WebSocket 连接
		this.initializeWebSocket();
	}

	// 初始化 WebSocket 连接
	initializeWebSocket() {
		if (!uni.getStorageSync("token")) return
		this.socketTask = uni.connectSocket({
			header: {
				'content-type': 'application/json',
				'token': uni.getStorageSync('token')
			},
			url: this.url,
			success: (res) => {
				this.isOpen = true;
				// 连接成功后启动心跳和消息监听
				this.startHeartbeat();
			},
			fail: (error) => {
				console.error('WebSocket连接失败', error);
				this.reconnect();
			}
		});
		this.socketTask.onMessage((res) => {
			var { data } = res;
			try {
				data = JSON.parse(data)
			} catch (error) {
				data = data
			}
			this.messageCallbacks.forEach(callback => callback(data));
		});
		this.socketTask.onClose((result) => {
			if (this.isWorking) {
				this.isOpen = false;
				this.reconnect();
			}
		});
	}

	// 启动心跳检测
	startHeartbeat() {
		if (this.heartbeatInterval) {
			clearInterval(this.heartbeatInterval);
		}
		this.heartbeatInterval = setInterval(() => {
			if (this.isOpen && uni.getStorageSync('token')) {
				this.send(JSON.stringify({ type: "heartbeat", token: uni.getStorageSync('token') }));
			}
		}, this.time * 1000);
	}

	// 发送消息
	send(data) {
		if (this.socketTask && this.isOpen) {
			this.socketTask.send({
				data: data,
				fail: (error) => {
					console.error('消息发送失败', error);
					this.reconnect(); // 这里可能需要根据实际情况判断是否重连
				}
			});
		}
	}

	// 重连 WebSocket
	reconnect() {
		if (this.reconnectTimeout) {
			clearTimeout(this.reconnectTimeout);
		}
		this.reconnectTimeout = setTimeout(() => {
			this.initializeWebSocket();
		}, 3000);
	}

	// 关闭 WebSocket 连接
	closeSocket() {
		if (this.socketTask) {
			this.socketTask.close({
				success: (res) => {
					this.isOpen = false;
				},
				fail: (error) => {
					console.error('关闭WebSocket连接失败', error);
				}
			});
			this.socketTask = null;
		}
	}

	// 外部注册消息回调函数
	onMessage(callback) {
		this.messageCallbacks.push(callback);
	}

	// 外部注销消息回调函数
	offMessage(callback) {
		this.messageCallbacks = this.messageCallbacks.filter(cb => cb !== callback);
	}

	// 销毁 WebSocket 连接，清理资源
	destroy() {
		this.isWorking = false;
		clearInterval(this.heartbeatInterval);
		clearTimeout(this.reconnectTimeout);
		this.closeSocket();
		this.messageCallbacks = [];
	}
}

export default WebsocketUtil;